package service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import object.PageBean;
import object.UserCenter;
import object.ZcAdmin;
import object.ZcOrderInfo;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pojo.LogIncome;
import pojo.LogNoruserbill;
import pojo.ZcArea;
import pojo.ZcItem;
import pojo.ZcOrder;
import pojo.ZcOrderItem;
import pojo.ZcOrderLog;
import pojo.ZcUser;
import pojo.ZcUserAddr;
import utils.OrderNumUtil;
import config.ConstantConfig;
import dao.Transaction2zcDao;
import dao.User2zcDao;

/**
 * 
 * @author zgy
 *
 */
@Service("Transaction2zcService")
public class Transaction2zcService {
	
	private static Logger logger = Logger.getLogger(Transaction2zcService.class);
	
	@Autowired
	private Transaction2zcDao transaction2zcDao;
	@Autowired
	private User2zcDao user2zcDao;
	
	
	//快递员登录
	public UserCenter adminLogin(String loginName,String loginPsd) {
		return user2zcDao.adminLogin(loginName, loginPsd);
	}
	
	//快递员登录
	public ZcAdmin getZcAdmin(String loginName) {
		return user2zcDao.getZcAdmin(loginName);
	}
	
	
	//根据wxid查找用户
	public ZcUser queryZcUser(String wxid) {
		return user2zcDao.getZcUser(wxid);
	}
	
	//保存用户
	public boolean saveZcUser(ZcUser e) {
		return user2zcDao.saveZcUser(e);
	}
	
	//areaId查询配送区域
	public ZcArea queryZcArea(Integer areaId){
		return transaction2zcDao.queryZcArea(areaId);
	}
	
	//根据UserId和areaId用户地址
	public List<ZcUserAddr> queryZcUserAddrsList(Integer userId,Integer areaId){
		return user2zcDao.queryZcUserAddr(userId,areaId);
	}
	
	//根据userid和areaId查找用户地址
	public ZcUserAddr queryZcUserAddr(Integer userId,Integer areaId) {
		return user2zcDao.getZcUserAddr(userId, areaId);
	}
	
	//根据UserId和areaId用户地址
	public ZcUserAddr queryZcUserAddrsById(Integer id){
		return user2zcDao.queryZcUserAddrById(id);
	}
		
	
	//保存用户地址
	public boolean saveZcUserAddr(ZcUserAddr e) {
		return user2zcDao.saveZcUserAddr(e);
	}
	
	//修改地址为默认地址
	public boolean editZcUserAddrToDef(Integer id) {
		return user2zcDao.editZcUserAddrToDef(id);
	}
	
	//保存用户地址
	@Transactional
	public boolean usaveZcUserAddr(ZcUserAddr e) {
		boolean flag=true;
		if("1".equals(e.getDef())){
			flag=user2zcDao.editZcUserAddrDef();
		}
		return user2zcDao.saveZcUserAddr(e)&&flag;
	}
	
	//修改用户地址
	@Transactional
	public boolean ueditZcUserAddr(ZcUserAddr e) {
		boolean flag=true;
		if("1".equals(e.getDef())){
			flag=user2zcDao.editZcUserAddrDef();
		}
		return user2zcDao.editZcUserAddr(e)&&flag;
	}
	
	//删除用户地址
	public boolean delZcUserAddr(Integer id) {
		return user2zcDao.delZcUserAddr(id);
	}
	
	//分页查询出早操配送区域
	public PageBean<ZcArea> queryLandmark(String city,Integer curPage,Integer pageSize){
		return transaction2zcDao.queryLandmark(city,curPage, pageSize);
	}

	//根据地区查询早餐列表
	public List<ZcItem> queryZcItems(Integer landmarkId){
		return transaction2zcDao.queryZcItems(landmarkId);
	}
	
	//根据UserId查询订单
	public List<ZcOrder> queryZcOrder(Integer userId,String status){
		return transaction2zcDao.queryZcOrder(userId,status);
	}
	
	//分页查询完成订单
	public PageBean<ZcOrder> queryZcOrderCompleted(Integer userId,Integer curPage,Integer pageSize){
		return transaction2zcDao.queryZcOrderCompleted(userId,curPage, pageSize);
	}
	
	//根据订单号查询订单
	public ZcOrder queryZcOrderByNum(String orderNum){
		return transaction2zcDao.queryZcOrderByNum(orderNum);
	}
	
	//保存订单
	@Transactional
	public String saveOrder(ZcOrderInfo o) throws ParseException{
		String orderNum=OrderNumUtil.createTradeNumber("JRZC");
		Integer userId=o.getUserId();
		String userArea= o.getUserArea();
		String userName=o.getUserName();
		String userMp= o.getUserMp();
		Integer userAreaId=o.getUserAreaId();
		String userAddress= o.getUserAddress();
		Calendar cl=Calendar.getInstance();
		int year=cl.get(Calendar.YEAR);
		Timestamp now=new Timestamp(cl.getTimeInMillis());
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
		ZcOrder order=new ZcOrder(null, orderNum, o.getItemSize(), o.getTotal(),now , 
				null, null, null, null, userId, userMp, userName, userAreaId, 
				userArea, userAddress,o.getRemark());
		transaction2zcDao.saveZcOrder(order);
		List<ZcOrderItem> list=new ArrayList<ZcOrderItem>();
		for (ZcItem item : o.getList()) {
			Date sdate = sdf.parse( year+"/"+item.getSellTime());
			Timestamp sendTime=new Timestamp(sdate.getTime());
			ZcOrderItem orderItem=new ZcOrderItem(null, item.getId(), item.getName(), item.getPrice(), 
					item.getSellCount(), orderNum, now, null, sendTime, null, userId, userMp, 
					userName, userAreaId, userArea, userAddress, null, null, null);
			list.add(orderItem);
		}
		transaction2zcDao.saveZcOrderItem(list);
		String log="【下单成功】";
		ZcOrderLog zclog=new ZcOrderLog(null, userMp, orderNum, now, log);
		transaction2zcDao.saveZcOrderLog(zclog);
		return orderNum;
	}
	
	//用户支付
	@Transactional
	public boolean payZcOrder(String orderNum,int payType){
		ZcOrder o = transaction2zcDao.queryZcOrderByNum(orderNum);
		if(ConstantConfig.TRANSACTION_NOTPAY.equals(o.getPayStatus())){
			if(transaction2zcDao.payZcorder(orderNum)){
				Timestamp now=new Timestamp(new Date().getTime());
				ZcOrderLog e=new ZcOrderLog(null, o.getUserMp(), orderNum, now, "【您已[微信]支付订单】");
				transaction2zcDao.saveZcOrderLog(e);
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	//要有事务,要锁行
	@Transactional
	public boolean editZcOrderStatus(String openId,String orderNum,String wxOrderNum,BigDecimal money){
		boolean flag=false;
		//BigDecimal balance=transaction2zcDao.queryUserBalance(openId);
		if(orderNum.indexOf("JRZCR")!=-1){
//			balance=balance.add(money.divide(new BigDecimal(100)));
//			flag=transaction2zcDao.updateLogIncomeStatus(orderNum, wxOrderNum,balance);
//			flag=transaction2zcDao.updateUserBalance(balance, openId);
		}else{
			BigDecimal balance=new BigDecimal(0);
			flag=transaction2zcDao.updateNorUserBillStatus(orderNum, wxOrderNum,balance );
			flag=payZcOrder(orderNum, ConstantConfig.PAYTYPE_WX);
		}
		return flag;
	}
	
	
	//根据订单号查询订单子项
	public List<ZcOrderItem> queryZcOrderItems(String orderNum){
		return transaction2zcDao.queryZcOrderItems(orderNum);
	}
	
	//查询快递员的配送订单
	public PageBean<ZcOrderItem> querySendItems(Integer suserId,Timestamp date,Timestamp date1,Integer curPage,Integer pageSize){
		return transaction2zcDao.querySendItems(suserId,date,date1,curPage,pageSize);
	}
	
	//结束配送订单
	@Transactional
	public String endSendItem(Integer id,Integer userId,String userMp){
		String result="OK";
		ZcOrderItem o= transaction2zcDao.querySendItemById(id);
		String orderNum=o.getOrderNum();
		String payStatus=o.getPayStatus();
		SimpleDateFormat df = new SimpleDateFormat("MM/dd");
		String sendTime=df.format(o.getSendTime());
		String desc="【"+sendTime+"早餐配送结束】";
		Integer count=transaction2zcDao.querySendItemCountByNum(o.getOrderNum());
		if(count==1){
			if("1".equals(payStatus)){
				transaction2zcDao.endZcorder(orderNum);
				desc="【订单结束】";
			}else{
				return "not pay";
			}
		}
		transaction2zcDao.endZcSendOrder(id);
		Timestamp now=new Timestamp(new Date().getTime());
		ZcOrderLog zclog=new ZcOrderLog(null, userMp, orderNum, now, desc);
		transaction2zcDao.saveZcOrderLog(zclog);
		return result;
		
	}
	
	//查询快递员根据用户手机查询订单
	public List<ZcOrderItem> querySendItemsByMp(Integer suserId,Timestamp date,String userMp){
		return transaction2zcDao.querySendItemsByMp(suserId,date,userMp);
	}
	
	//根据订单号查询订单日志
	public List<ZcOrderLog> queryZcOrderLog(String orderNum){
		return transaction2zcDao.queryZcOrderLog(orderNum);
	}
	
	

	
	
	

	
	public List<LogNoruserbill> queryUserBillList(Integer userId){
		return transaction2zcDao.queryUserBillList(userId);
	}
	
	public List<LogIncome> queryIncomeList(Integer userId){
		return transaction2zcDao.queryIncomeList(userId);
	}
	
	
	

	


	
	public boolean insertLogBill(String platformId,String userMp,String orderNum,BigDecimal money){
		boolean flag=false;
		//UserCenter userCenter=queryUserCenter(platformId);
		if(orderNum.indexOf("JRZCR")!=-1){
			/*LogIncome income=new LogIncome(new Integer(5),userCenter.getUserId(),
					userCenter.getLastName()+userCenter.getFirstName(),
					new Integer(1),userCenter.getUserId(),
					new Timestamp(new Date().getTime()),money,
					new BigDecimal(0),ConstantConfig.PAYTYPE_WX,orderNum,ConstantConfig.TRANSACTION_NOTPAY);
			flag=transaction2zcDao.insertLogIncome(income);*/
		}else{
			Integer count=transaction2zcDao.queryNorUserBillCount(orderNum);
			if(!(count>0)){
				LogNoruserbill noruserbill=new LogNoruserbill(null, new Timestamp(new Date().getTime()), 
						money, new BigDecimal(0), ConstantConfig.LogNorUSerBill_XY, 
						"【今日早餐扣费】", ConstantConfig.PAYTYPE_WX, userMp, 
						orderNum,ConstantConfig.LogNorUSerBill_WXPAY, ConstantConfig.TRANSACTION_NOTPAY);
				flag=transaction2zcDao.insertNorUserBill(noruserbill);
			}else{
				flag=true;
			}
		}
		return flag;
	}
	
/*	@Transactional
	public boolean ybPayTransaction(String openId,String orderNum,BigDecimal money){
		boolean flag=false;
		UserCenter userCenter=queryUserCenter(openId);
		BigDecimal balance=userCenter.getBalance();
		if(balance.compareTo(money)!=-1){
			balance=balance.subtract(money) ;
			LogNoruserbill noruserbill=new LogNoruserbill(userCenter.getUserId(), new Timestamp(new Date().getTime()), 
					money,balance , ConstantConfig.LogNorUSerBill_XY, 
					"【邮宝洗衣扣费】", ConstantConfig.PAYTYPE_YB, userCenter.getMobileNum(), 
					OrderNumUtil.createTradeNumber(),ConstantConfig.LogNorUSerBill_COUNTPAY, ConstantConfig.TRANSACTION_PAYED);
			flag=transaction2zcDao.insertNorUserBill(noruserbill);
			flag=transaction2zcDao.updateUserBalance(balance, openId);
			flag=payZcOrder(orderNum,ConstantConfig.PAYTYPE_YB);
		}
		return flag;
		
	}*/


	
}